package org.busalerter.ui;

import ca.odell.glazedlists.BasicEventList;
import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.swing.EventSelectionModel;
import ca.odell.glazedlists.swing.EventTableModel;
import org.busalerter.domain.BusStop;
import org.busalerter.repo.BusStopRepo;
import org.busalerter.repo.BusStopRepoImpl;

import static org.busalerter.ui.SwingUtils.*;

import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * Display a list of bus-stops to select from to display times for
 *
 * bit of a mess in here - separate model
 *
 * also should revert selection on cancel
 *
 * User: Andy
 * Date: 20/11/11
 * Time: 19:13
 */
public class BusStopSelectorDialog extends JDialog {


    private EventTableModel<BusStop> busStopTableModel;
    private EventList<BusStop> busStops;
    private EventSelectionModel<BusStop> selectionModel;

    // components
    private JTable busStopTable;


    public BusStopSelectorDialog(JFrame parent) {

        super(parent);


        this.setTitle("Select Bus Stop");
        this.setModal(true);


        BusStopRepo busStopRepo = new BusStopRepoImpl();

        busStops = new BasicEventList<BusStop>();
        busStops.addAll(busStopRepo.getBusStops());

        busStopTableModel = new EventTableModel<BusStop>(busStops, new BusStopTableFormat());

        selectionModel = new EventSelectionModel<BusStop>(busStops);
        selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);


        // display table list
        busStopTable = new JTable(busStopTableModel);
        busStopTable.setSelectionModel(selectionModel);

        busStopTable.getColumnModel().getColumn(0).setPreferredWidth(500);
        busStopTable.getColumnModel().getColumn(1).setPreferredWidth(75);

        // add event handler to select table item

        busStopTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {

                if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
                    // on double click just close dialog
                    BusStopSelectorDialog.this.setVisible(false);
                }
            }
        });


        this.add(busStopTable);
        this.pack();
        setResizable(false);
    }

    public void open() {
        setVisible(true);
    }

    public BusStop getCurrentBusStop() {
        EventList<BusStop> selectedItems = selectionModel.getSelected();
        if (selectedItems.size() > 0) {
            return selectedItems.get(0);
        }

        // default to first item
        return busStops.get(0);
    }


}
